from . import admins_bp
from .forms.tag import EditForm, GoodForm
from ...models import Tag, db
from ...helper import redirect_back
from flask import render_template, flash, request


@admins_bp.route('/tag', methods=['GET', 'POST'])
def tag_select():
    query = Tag.query
    title = request.args.get('title', type=str, default=None)
    if title:
        query = query.filter(Tag.tag_name.like('%{}%'.format(title.strip())))
    record = query.paginate(per_page=12)
    form = GoodForm()
    if form.validate_on_submit():
        # 批量推荐或取消推荐
        tag_ids = list(map(int, request.form.getlist('tag_ids')))
        if tag_ids:
            with db.auto_commit():
                for _t in record.items:
                    print(_t.id)
                    if _t.id in tag_ids:
                        _t.good = 1 if form.confirm_good.data else 0
            flash('操作成功', 'success')
        else:
            flash('请选择Tags', 'info')
    return render_template('tag_select.html', page_title='标签管理', record=record)


@admins_bp.route('tag/create', methods=['GET', 'POST'])
def tag_create():
    form = EditForm()
    if form.validate_on_submit():
        with db.auto_commit():
            t = Tag()
            t.set_fields(form.data)
            db.session.add(t)
        flash('Tag新增成功', 'success')
        return redirect_back('admins.tag_select')
    return render_template('tag_edit.html', page_title='Tag信息', form=form)


@admins_bp.route('tag/<int:tag_id>', methods=['GET', 'POST'])
def tag_modify(tag_id):
    _t = Tag.query.get_or_404(tag_id)
    form = EditForm(**_t.__dict__)
    if form.validate_on_submit():
        with db.auto_commit():
            _t.set_fields(form.data)
        flash('Tag更新成功', 'success')
        return redirect_back('.tag_select')
    return render_template('tag_edit.html', page_title='Tag信息', form=form)
